package stu.day25_day32.day30;

import java.util.Scanner;

public class hw2 {

    public static int max=0;



    public static void backtrack(int[][] array,int[][] flag,int i,int j,int len,int num,boolean isUp){

        int n = array.length;
        int m = array[0].length;

        if( i>=0 && i<n && j>=0 && j<m){
            if(isUp){
                if(array[i][j]>num && flag[i][j]==0){
                    flag[i][j] = 1;
                    max = Math.max(max,len+1);
                    backtrack(array,flag,i+1,j,len+1,array[i][j],false);
                    backtrack(array,flag,i-1,j,len+1,array[i][j],false);
                    backtrack(array,flag,i,j+1,len+1,array[i][j],false);
                    backtrack(array,flag,i,j-1,len+1,array[i][j],false);
                    flag[i][j] = 0;
                }

            }else {
                if(array[i][j]<num && flag[i][j]==0){
                    flag[i][j] = 1;
                    backtrack(array,flag,i+1,j,len+1,array[i][j],true);
                    backtrack(array,flag,i-1,j,len+1,array[i][j],true);
                    backtrack(array,flag,i,j+1,len+1,array[i][j],true);
                    backtrack(array,flag,i,j-1,len+1,array[i][j],true);
                    flag[i][j] = 0;
                }

            }

        }

    }



    public static void main(String[] args) {
        // 数据输入
        Scanner sc = new Scanner(System.in);
        String[] s1 =sc.nextLine().split(" ");
        int n = Integer.parseInt(s1[0]);
        int m = Integer.parseInt(s1[1]);

        int[][] array = new int[n][m];
        for(int i=0;i<n;i++){
            String[] s2 =sc.nextLine().split(" ");
            for(int j=0;j<m;j++){
                array[i][j] = Integer.parseInt(s2[j]);
            }
        }

        // 数据
        int[][] flag = new int[n][m];


        // 回溯
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                backtrack(array,flag,i,j,0,Integer.MIN_VALUE,true);
                backtrack(array,flag,i,j,0,Integer.MAX_VALUE,false);
            }
        }

        System.out.println(max-1);




    }



}
